package edu.ntu.im.p2ptrade.msg;

import java.util.List;

import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.entity.ItemRepository;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.StringMessageElement;

public class MyItems implements PMessage {

	public static final String IID = "iid";
	public static final String INAME = "iname";
	public static final String IMEMO = "imemo";
	public static final String IPICURL = "ipicurl";

	public Message getMessageToTransfer() {
		Message msg = new Message();
		msg.addMessageElement(P2PTrade.getInstance().getAppName(),
				new StringMessageElement(PEER, P2PTrade.getInstance().getPeerName(), null));
		List<Item> myItems = ItemRepository.getInstance().getItems();
		Items2Message(msg, myItems);
		msg
		.addMessageElement(P2PTrade.getInstance().getAppName(),
				new StringMessageElement(TYPE,MyItems.class
						.getSimpleName(), null));
		return msg;
	}

	static void Items2Message(Message msg, List<Item> myItems) {
		for (Item item:myItems){
			msg.addMessageElement(P2PTrade.getInstance().getAppName(),
					new StringMessageElement(IID, item.getId().toString(), null));
			msg.addMessageElement(P2PTrade.getInstance().getAppName(),
					new StringMessageElement(INAME, item.getName(), null));
			msg.addMessageElement(P2PTrade.getInstance().getAppName(),
					new StringMessageElement(IMEMO, item.getMemo(), null));
			msg.addMessageElement(P2PTrade.getInstance().getAppName(),
					new StringMessageElement(IPICURL, item.getPhotoUrl(), null));
		}
		

	}

	public String toLogMessage() {
		StringBuffer sb = new StringBuffer();
		sb.append("my items:[");
		for (Item item:ItemRepository.getInstance().getItems()){
			sb.append(item.toString());
		}
		sb.append("]");
		return sb.toString();
	}

}
